#include "cmd.h"

int setPath(user_session_t *pUserSession)
{
    char query[1024];
    snprintf(query, sizeof(query), "select path from files where id = '%d'", pUserSession->pStack->pTop->file_id);
    if (mysql_query(pUserSession->conn, query) != 0)
    {
        fprintf(stderr, "QUERY FAILED: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }
    MYSQL_RES *result = mysql_store_result(pUserSession->conn);
    if (result == NULL)
    {
        fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    char path[1024] = {0};
    if (row != NULL)
    {
        strcpy(path, row[0]);
    }
    strcpy(pUserSession->path, path);
    tlv_msg_t msg;
    bzero(&msg, sizeof(msg));
    char value[1024];
    strcat(value, path);
    strcpy(pUserSession->path,path);

    return 0;
}
int checkDel(user_session_t *pUserSession)
{
    char query[1024];
    snprintf(query, sizeof(query), "select filename from files where parent_id = '%d' AND username = '%s'", pUserSession->pStack->pTop->file_id, pUserSession->username); // 父亲id
    printf("file_id = %d\n", pUserSession->pStack->pTop->file_id);
    if (mysql_query(pUserSession->conn, query) != 0)
    {
        fprintf(stderr, "Query failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }
    MYSQL_RES *result = mysql_store_result(pUserSession->conn);
    if (result == NULL)
    {
        fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }
    MYSQL_ROW row;
    char fileds[1024] = {0};
    while ((row = mysql_fetch_row(result)) != NULL)
    {
        strcat(fileds, row[0]);
        strcat(fileds, " ");
    }
    if (strlen(fileds) != 0)
    {
        return 0; // 不能删
    }
    return 1; // 可以删
}
int getPath(MYSQL *mysql, int file_id, char *path) // 根据文件id查找路径
{
    char query[1024];
    snprintf(query, sizeof(query), "select path from files where id = '%d'", file_id);

    if (mysql_query(mysql, query) != 0)
    {
        fprintf(stderr, "Query failed: %s\n", mysql_error(mysql));
        exit(-1);
    }

    MYSQL_RES *result = mysql_store_result(mysql);
    if (result == NULL)
    {
        fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(mysql));
        exit(-1);
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    if (row != NULL)
    {
        strcpy(path, row[0]);
        mysql_free_result(result);
        return 0;
    }
    else
    {
        mysql_free_result(result);
        return 0; // 未找到
    }
}
int insertMysql(user_session_t *pUserSession, char *filename) // 插入mysql
{
    char query[4096] = {0};
    char path[1024] = {0};
    int parent_id = pUserSession->pStack->pTop->file_id;
    getPath(pUserSession->conn, parent_id, path); // 根据父亲id查找路径
    int len = strlen(path);
    if (path[len - 1] != '/')
    {
        strcat(path, "/");
    }
    strcat(path, filename);
    snprintf(query, sizeof(query), "insert into files (parent_id,filename,user_id,username,type,path) values ('%d','%s','%d','%s','d','%s')", parent_id, filename, pUserSession->user_id, pUserSession->username, path);
    int qres = mysql_query(pUserSession->conn, query);
    if (qres != 0)
    {
        fprintf(stderr, "Query failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }

    return 0;
}
int getFileId(user_session_t *pUserSession, char *filename) // 通过文件名查找文件id
{
    char query[1024];
    int file_id;
    snprintf(query, sizeof(query), "select id,parent_id from files where filename = '%s' AND username = '%s'", filename, pUserSession->username);

    if (mysql_query(pUserSession->conn, query) != 0)
    {
        fprintf(stderr, "Query failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }

    MYSQL_RES *result = mysql_store_result(pUserSession->conn);
    if (result == NULL)
    {
        fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }
    printf("进入getFileId\n");
    MYSQL_ROW row = mysql_fetch_row(result);
    // printf("%s\n", row[0]);
    if (row != NULL && atoi(row[1]) == pUserSession->pStack->pTop->file_id)
    {
        file_id = atoi(row[0]);
        printf("file_id = %d\n", file_id);
        mysql_free_result(result);
        return file_id;
    }
    else
    {
        mysql_free_result(result);
        return 0; // 未找到
    }
}
int handleAbsolutePath(user_session_t *pUserSession, const char *path) // 处理绝对路径
{
    tlv_msg_t msg;
    char value[1024] = {0};
    folderStackDestroy(pUserSession->pStack); // 处理绝对路径时先将栈清空
    push(pUserSession->pStack, 1);            // 将根目录压栈

    char temp[1024] = {0}; // 创建临时变量保存路径
    strcpy(temp, path);

    char *component = strtok(temp + 1, "/"); // 从根目录开始向后查找/
    while (component != NULL)                // 直到component不为空一直查找
    {
        if (strcmp(component, ".") == 0) // exampel: /.
        {
            // 还是在当前目录
        }
        else if (strcmp(component, "..") == 0) // example /..
        {
            if (pUserSession->pStack->stackSize > 1) // 如果目前栈大小大于1弹栈
            {
                pop(pUserSession->pStack);
            }
        }
        else // example: /dir1
        {
            printf("component = %s\n", component);            // 测试打印
            int file_id = getFileId(pUserSession, component); // 根据文件名获取文件id
            if (file_id == 0)                                 // 判断路径是否错误
            {
                printf("1231423423\n");
                bzero(&msg, sizeof(msg));
                strcpy(value, "输入的路径错误");
                tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
                tlv_send(pUserSession->netfd, &msg);
                printf("输入的路径错误\n"); // 服务端测试打印
                return 0;
            }
            else
            {
                push(pUserSession->pStack, file_id); // 将file_id入栈
                printf("cd后栈顶为%d\n", pUserSession->pStack->pTop->file_id);
            }
        }
        component = strtok(NULL, "/"); // 持续向后查找
    }
    bzero(&msg, sizeof(msg));
    strcpy(value, "进入目录成功");
    tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
    tlv_send(pUserSession->netfd, &msg);
    return 0;
}
int handleRelativePath(user_session_t *pUserSession, const char *path) // 处理相对路径
{
    tlv_msg_t msg;
    char value[1024];
    char temp[1024] = {0};
    strcpy(temp, path);

    char *component = strtok(temp, "/"); // 向后查找/
    while (component != NULL)
    {
        if (strcmp(component, ".") == 0)
        {
            // 还是在当前目录
        }
        else if (strcmp(component, "..") == 0)
        {
            if (pUserSession->pStack->stackSize > 1)
            {
                pop(pUserSession->pStack);
            }
        }
        else
        {
            printf("component = %s\n", component);
            int file_id = getFileId(pUserSession, component);
            if (file_id == 0)
            {
                bzero(&msg, sizeof(msg));
                strcpy(value, "输入的路径错误");
                tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
                tlv_send(pUserSession->netfd, &msg);
                printf("输入的路径错误\n"); // 服务端测试打印
                return 0;
            }
            else
            {
                push(pUserSession->pStack, file_id); // 将file_id入栈
            }
        }
        component = strtok(NULL, "/");
    }
    bzero(&msg, sizeof(msg));
    strcpy(value, "进入目录成功");
    tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
    tlv_send(pUserSession->netfd, &msg);
    return 0;
}
int changeDirectory(user_session_t *pUserSession, char *path) // 判断处理绝对路径or相对路径
{
    if (path[0] == '/') // 进入绝对目录处理
    {
        printf("进入changeDirectory\n"); // 测试打印
        handleAbsolutePath(pUserSession, path);
    }
    else // 进入相对目录处理
    {
        printf("进入changeDirectory\n"); // 测试打印
        handleRelativePath(pUserSession, path);
    }
    return 0;
}
// cd函数调用过程 cdFunc--->changeDirectroy--->handleAbsolutePath/handleRelativePath--->getFileId--->
int cdFunc(user_session_t *pUserSession, char *buf)
{
    tlv_msg_t msg;
    char value[1024] = {0};
    printf("进入cd\n");
    printf("buf = %s\n", buf);
    if (strcmp(buf, "/") == 0 || strcmp(buf, " ") == 0) // 输入cd / 或者 cd 返回根目录
    {
        folderStackDestroy(pUserSession->pStack);
        push(pUserSession->pStack, 1);
        bzero(&msg, sizeof(msg));
        strcpy(value, "进入目录成功");
        tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
        tlv_send(pUserSession->netfd, &msg);
        return 0;
    }
    else if (strcmp(buf, "..") == 0) // 输入cd ..返回上一级
    {
        if (pUserSession->pStack->stackSize <= 1) // 目前在根目录
        {
            bzero(&msg, sizeof(msg));
            strcpy(value, "目前已经为根目录");
            printf("value = %s\n", value);
            tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
            tlv_send(pUserSession->netfd, &msg);
            return 0;
        }
        else
        {
            printf("栈顶为%d\n", pUserSession->pStack->pTop->file_id);
            pop(pUserSession->pStack); // 不在根目录一律弹出栈顶
            printf("栈顶为%d\n", pUserSession->pStack->pTop->file_id);
            bzero(&msg, sizeof(msg));
            strcpy(value, "返回上级目录成功");
            tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
            tlv_send(pUserSession->netfd, &msg);
        }
    }
    else if (strcmp(buf, ".") == 0) // 在当前目录
    {
        bzero(&msg, sizeof(msg));
        strcpy(value, "保持当前目录");
        tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
        tlv_send(pUserSession->netfd, &msg);
        return 0;
    }
    else
    {
        changeDirectory(pUserSession, buf); // 判断处理绝对路径or相对路径
    }
    setPath(pUserSession);

    return 0;
}
int pwdFunc(user_session_t *pUserSession)
{
    printf("进入pwdFunc\n");
    char query[1024];
    snprintf(query, sizeof(query), "select path from files where id = '%d'", pUserSession->pStack->pTop->file_id);
    if (mysql_query(pUserSession->conn, query) != 0)
    {
        fprintf(stderr, "QUERY FAILED: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }
    MYSQL_RES *result = mysql_store_result(pUserSession->conn);
    if (result == NULL)
    {
        fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }

    MYSQL_ROW row = mysql_fetch_row(result);
    char path[1024] = {0};
    if (row != NULL)
    {
        strcpy(path, row[0]);
    }
    printf("%s\n", path);
    strcpy(pUserSession->path, path);
    tlv_msg_t msg;
    bzero(&msg, sizeof(msg));
    char value[1024];
    strcpy(value, "当前目录为：");
    strcat(value, path);
    tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
    tlv_send(pUserSession->netfd, &msg);
    return 0;
}
int lsFunc(user_session_t *pUserSession)
{
    char query[1024];
    snprintf(query, sizeof(query), "select filename from files where parent_id = '%d' AND username = '%s'", pUserSession->pStack->pTop->file_id, pUserSession->username); // 父亲id
    printf("file_id = %d\n", pUserSession->pStack->pTop->file_id);
    if (mysql_query(pUserSession->conn, query) != 0)
    {
        fprintf(stderr, "Query failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }
    MYSQL_RES *result = mysql_store_result(pUserSession->conn);
    if (result == NULL)
    {
        fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(pUserSession->conn));
        exit(-1);
    }
    MYSQL_ROW row;
    char fileds[1024] = {0};
    strcat(fileds,"当前目录下文件为：");
    while ((row = mysql_fetch_row(result)) != NULL)
    {
        strcat(fileds, row[0]);
        strcat(fileds, " ");
    }
    tlv_msg_t msg;
    bzero(&msg, sizeof(msg));
    tlv_create(&msg, CMD_RESPONSE, strlen(fileds), fileds);
    tlv_send(pUserSession->netfd, &msg);

    return 0;
}
int mkdirFunc(user_session_t *pUserSession, const char *path)
{
    insertMysql(pUserSession, path);
    tlv_msg_t msg;
    char value[1024] = {0};
    strcpy(value, "创建文件夹成功");
    bzero(&msg, sizeof(msg));
    tlv_create(&msg, CMD_RESPONSE, strlen(value), value);
    tlv_send(pUserSession->netfd, &msg);
    return 0;
}
int rmdirFunc(user_session_t *pUserSession, const char *path)
{

    int canDel = checkDel(pUserSession);
    // to do

    // char query[1024];
    // snprintf(query, sizeof(query), "select filename from files where parent_id = '%d' AND filename = '%s' AND username = '%s'", pUserSession->pStack->pTop->file_id, path,pUserSession->username);
    // int qret = mysql_query(pUserSession->conn, query);
    // if (qret != 0)
    // {
    //     fprintf(stderr, "Query failed: %s\n", mysql_error(pUserSession->conn));
    //     exit(-1);
    // }
    // MYSQL_RES *result = mysql_store_result(pUserSession->conn);
    // if (result == NULL)
    // {
    //     fprintf(stderr, "mysql_store_result() failed: %s\n", mysql_error(pUserSession->conn));
    //     exit(-1);
    // }
    // MYSQL_ROW row = mysql_fetch_row(result);
}
